<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      row-key="onlyId"
      :key="timer"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="" slot="operatornameSearch">
        <el-input placeholder="请选择 操作人员" readonly="true" v-model="search.operatorName">
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getInventoryInfo } from '@/api/warehouse/transaction';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'TRANSACTION',
      form: {},
      query: {},
      loading: false,
      inventoryType: '',
      isLock: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      timer: new Date().getTime(),
      search: {}, //搜索条件
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        addBtn: false, //新增按钮是否显示
        menu: false, //表格操作栏是否显示
        searchSpan: 4,
        columnBtn: false,
        column: [
          {
            label: '事务时间',
            prop: 'transactionTime',
            search: true,
            width: 130,
            searchOrder: 7,
            searchSpan: 8,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '事务类型',
            prop: 'transactionType',
            search: true,
            searchOrder: 3,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=transaction_type'
          },
          {
            label: '物料编码',
            prop: 'partCode',
            search: true,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          // {
          //   label: '物料型号',
          //   prop: 'partModel'
          // },
          {
            label: '物料批次',
            prop: 'lotNo',
            search: true,
            searchOrder: 5
          },
          {
            label: '包装条码',
            prop: 'packingPackNo',
            search: true,
            searchOrder: 6
          },
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '库存中心',
            prop: 'inventoryId',
            search: true,
            searchOrder: 1,
            type: 'select',
            hide: true,
            dicData: [],
            props: {
              label: 'name',
              value: 'id'
            },
            cascader: ['areaId']
            // control: (val) => {
            //     console.log(val, 'valval')
            //     this.deptId = val;
            // }
          },
          {
            label: '储位名称',
            prop: 'areaId',
            search: true,
            searchOrder: 2,
            type: 'select',
            hide: true,
            dicFlag: false,
            dicUrl: '/api/mes-admin/area/select/inventory?inventoryId={{key}}',
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '储位名称',
            prop: 'areaName'
          },
          // {
          //   label: '原数量',
          //   prop: 'originalQuantity'
          // },
          {
            label: '事务数量',
            prop: 'quantity',
            html: true,
            formatter: (val) => {
              if (val.quantity.indexOf('-') != -1) {
                return `<span class="text-green">${val.quantity}</span>`;
              } else {
                return `<span class="text-red">+${val.quantity}</span>`;
              }
            }
          },
          {
            label: '结余数量',
            prop: 'remainingQuantity'
          },
          // {
          //   label: '当前数量',
          //   prop: 'remainingQuantity'
          // },
          {
            label: '单据号',
            prop: 'sheetNo',
            width: 120
          },
          {
            label: '状态',
            prop: 'status',
            dicData: [
              {
                label: '成功',
                value: 1
              },
              {
                label: '已入库待上架',
                value: 2
              },
              {
                label: '已入库上架',
                value: 3
              },
              {
                label: '失败',
                value: 0
              }
            ]
          },
          {
            label: '操作人员',
            prop: 'operatorName',
            search: true,
            searchOrder: 8,
            searchType: 'search',
            formslot: true,
            appendClick: () => {
              this.openUserCommonModal();
            }
          }
        ]
      },
      data: [],
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      deptId: '',
      customAttributeList: [], //扩展属性
      oldColumn: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.transaction_add, false),
        viewBtn: this.vaildData(this.permission.transaction_view, false),
        delBtn: this.vaildData(this.permission.transaction_delete, false),
        editBtn: this.vaildData(this.permission.transaction_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.oldColumn = this._cloneDeep(this.option.column);
    let path = this.$route.path;
    getAttributeConfigList(path).then((res) => {
      this.customAttributeList = this._get(res, 'data.data', []);
      this._forEach(this.customAttributeList, (item, index) => {
        this.option.column.splice(5 + index, 0, {
          label: item.lableCnName,
          prop: item.attributeKey,
          type: item.controlType,
          value: item.defaultValue,
          dispaly: item.enabled
        });
      });
      this.$refs.crud.refreshTable();
    });
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.transactionTime && params.transactionTime.length > 0) {
        params.startTransactionDate = params.transactionTime[0];
        params.endTransactionDate = params.transactionTime[1];
        delete params.transactionTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      // let isEmpty = true;
      // Object.keys(this.search).forEach((x) => {
      //   if (this.search[x] != null && this.search[x] != '') {
      //     isEmpty = false;
      //   }
      // });
      // if (!isEmpty) {
      this.loading = true;
      delete params.operatorName;
      if (this.$route.path === '/warehouse/transaction/1') {
        params.partType = 'MATERIAL';
      } else if (this.$route.path === '/warehouse/transaction/2') {
        params.partType = 'SEMIFINISHED,PRODUCT';
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item, index) => {
          item.sheetNo = item.sheetNo || item.checkingPlanNo;
        });
        this.loading = false;
        this.selectionClear();
      });
      // } else {
      //   this.$message({
      //     type: 'warning',
      //     message: '请输入至少一个查询条件!'
      //   });
      //   this.loading = false;
      //   this.page.total = 0;
      //   this.data = [];
      // }
    },
    /**
     * 打开操作人员列表模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操作人员（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'userModal') {
        this.search.operator = this._get(rowData, 'id', '');
        this.search.operatorName = this._get(rowData, 'realName', '');
      }
    },
    getInventoryInfo() {
      const column = this.findObject(this.option.column, 'inventoryId');
      column.dicData = [];
      getInventoryInfo({ inventoryType: this.inventoryType }).then((res) => {
        let data = res.data.data || [];
        column.dicData = data;
      });
    },
    getInventoryType() {
      if (this.$route.path === '/warehouse/transaction/1') {
        this.inventoryType = 'MATERIAL';
      } else if (this.$route.path === '/warehouse/transaction/2') {
        this.inventoryType = 'PRODUCT';
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  },
  mounted() {
    if (this.isLock) {
      this.onLoad(this.page);
      this.getInventoryType();
      this.getInventoryInfo();
      this.$nextTick(() => {
        this.$structuralSplit();
      });
    }
  },
  watch: {
    async $route() {
      let whiteList = ['/warehouse/transaction/1', '/warehouse/transaction/2'];
      if (whiteList.includes(this.$route.path)) {
        this.isLock = false;
        this.newKey();
        this.getInventoryType();
        this.getInventoryInfo();
        this.query = {};
        this.search = {};
        await this.onLoad(this.page);
        let path = this.$route.path;
        this.option.column = this._cloneDeep(this.oldColumn);
        if (this.$route.path === '/warehouse/transaction/1') {
          getAttributeConfigList(path).then((res) => {
            this.customAttributeList = this._get(res, 'data.data', []);
            this._forEach(this.customAttributeList, (item, index) => {
              this.option.column.splice(5 + index, 0, {
                label: item.lableCnName,
                prop: item.attributeKey,
                type: item.controlType,
                value: item.defaultValue,
                dispaly: item.enabled
              });
            });
          });
        }
        this.$refs.crud.refreshTable();
        this.$nextTick(() => {
          this.$structuralSplit();
        });
      }
    }
  }
};
</script>

<style></style>
